package com.beerandjesus.sportofkings.handicapper.strategy.brisnet.singlefile;

import com.beerandjesus.sportofkings.handicapper.model.NonMaidenHorseAnalysisResultImpl;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.PastPerformance;
import com.beerandjesus.sportofkings.handicapper.strategy.RacingCalculator;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;

public class UpCloseWhenStalkingResolver {
    private static final int MAX_RACES_FOR_UP_CLOSE_CONSIDERATION = 8;
    private static final BigDecimal TWO_AND_THREE_QUARTERS = new BigDecimal("2.75");
    private static final BigDecimal THREE_AND_A_HALF = new BigDecimal("3.5");
    private RacingCalculator calc = new RacingCalculator();


    public UpCloseWhenStalkingResolver() {
    }

    void resolveUpCloseWhenStalking(NonMaidenHorseAnalysisResultImpl result, Horse h) {
        // Up close 2 times within last 8 races
        // up close =
        // 2 3/4 lengths at 2nd call for sprints
        // 3 1/2 lengths at 2nd call for routes
        int upCloseCount = 0;
        int raceCount = 0;
        for (PastPerformance perf : h.getPastPerformances()) {
            raceCount++;
            if (raceCount > MAX_RACES_FOR_UP_CLOSE_CONSIDERATION) {
                break;
            }
            String lenOrMarg = perf.getCall2ndLenOrMargin();
            if (!StringUtils.isEmpty(lenOrMarg)) {
                BigDecimal lengthOrMargin = new BigDecimal(lenOrMarg);
                BigDecimal upCloseComparison;
                if (calc.isRoute(perf.getDistance())) {
                    upCloseComparison = THREE_AND_A_HALF;
                } else {
                    upCloseComparison = TWO_AND_THREE_QUARTERS;
                }
                if (lengthOrMargin.compareTo(upCloseComparison) <= 0) {
                    upCloseCount++;
                }
            }
        }
        boolean upClose = false;
        if (upCloseCount > 1) {
            upClose = true;
        }
        result.setUpCloseWhenStalking(upClose);
    }
}